<template>
  <main class="h-full flex flex-col max-w-7xl mx-auto px-6 pb-2">
    <!-- 顶部标题 -->
    <div class="flex-shrink-0 mb-4">
      <div class="flex items-center gap-2">
        <div class="w-2 bg-yellow-200 h-8"></div>
        <h1 class="text-2xl font-bold mb-2">AI图片扩展</h1>
      </div>
      <p class="text-gray-600 text-sm">基于选中的图片智能扩展生成相似图片</p>
    </div>
    <div class="flex gap-6 flex-1 min-h-0">
      <!-- 左侧配置区域 -->
      <ScrollArea
        class="w-100 rounded-md border p-4 h-[600px] flex-shrink-0 bg-white"
      >
        <div class="space-y-6">
          <div class="bg-white rounded-lg border p-4">
            <div class="flex items-center gap-2">
              <div class="text-lg font-semibold mb-1">基础图片</div>
              <svg
                t="1753020669006"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="25117"
                width="30"
                height="30"
              >
                <path
                  d="M125.9 185h772.2v653.9H125.9z"
                  fill="#1F53CC"
                  p-id="25118"
                ></path>
                <path
                  d="M164.7 217.2h694.6v516.7H164.7z"
                  fill="#FECD44"
                  p-id="25119"
                ></path>
                <path
                  d="M458.9 734l-8.6-43.8-101.5-102.8-135 146.6z"
                  fill="#FC355D"
                  p-id="25120"
                ></path>
                <path
                  d="M306.9 348.7m-66.7 0a66.7 66.7 0 1 0 133.4 0 66.7 66.7 0 1 0-133.4 0Z"
                  fill="#FFFFFF"
                  p-id="25121"
                ></path>
                <path
                  d="M384.6 734h474.7V608.8L687.8 400.1z"
                  fill="#FC355D"
                  p-id="25122"
                ></path>
                <path
                  d="M422.5 662l-37.9 72 52.1-57.5z"
                  fill="#BF2847"
                  p-id="25123"
                ></path>
                <path
                  d="M302.5 778.9h418.9v16.7H302.5z"
                  fill="#00F0D4"
                  p-id="25124"
                ></path>
              </svg>
            </div>

            <div v-if="selectedImage" class="space-y-3">
              <div class="relative">
                <img
                  :src="selectedImage.url"
                  :alt="selectedImage.name"
                  class="w-full h-48 object-cover rounded-lg border"
                />
                <div
                  class="absolute top-2 right-2 bg-black/70 text-white px-2 py-1 rounded text-xs"
                >
                  已选择
                </div>
              </div>
              <div>
                <div class="flex items-center gap-2">
                  <h4 class="font-medium text-gray-900">
                    {{ selectedImage.originalName.split(".")[0] }}
                  </h4>
                  <Badge variant="secondary">
                    {{ selectedImage.originalName.split(".")[1] }}
                  </Badge>
                </div>
                <p class="text-sm text-gray-600 mt-1">
                  上传时间: {{ formatDate(selectedImage.uploadTime) }}
                </p>
                <div class="flex flex-wrap gap-1 mt-2">
                  <span
                    v-for="tag in selectedImage.tags"
                    :key="tag"
                    class="bg-gray-100 text-gray-700 px-2 py-1 rounded text-xs"
                    >{{ tag }}</span
                  >
                </div>
              </div>
            </div>
            <div
              v-else
              class="text-center py-8 text-gray-500 flex flex-col items-center"
            >
              <svg
                t="1753020164191"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="12227"
                width="150"
                height="150"
              >
                <path
                  d="M829.64898 849.502041H194.35102c-43.885714 0-79.412245-35.526531-79.412244-79.412245V253.910204c0-43.885714 35.526531-79.412245 79.412244-79.412245h635.29796c43.885714 0 79.412245 35.526531 79.412244 79.412245v516.179592c0 43.885714-35.526531 79.412245-79.412244 79.412245z"
                  fill="#D2F4FF"
                  p-id="12228"
                ></path>
                <path
                  d="M909.061224 656.195918l-39.706122-48.065306L626.416327 365.714286c-19.330612-19.330612-50.677551-19.330612-70.008164 0L419.526531 502.073469c-2.612245 2.612245-5.22449 3.134694-6.791837 3.134694-1.567347 0-4.702041-0.522449-6.791837-3.134694L368.326531 464.979592c-19.330612-19.330612-50.677551-19.330612-70.008164 0l-143.673469 143.673469-39.706122 48.065306v113.893878c0 43.885714 35.526531 79.412245 79.412244 79.412245h635.29796c43.885714 0 79.412245-35.526531 79.412244-79.412245v-114.416327"
                  fill="#16C4AF"
                  p-id="12229"
                ></path>
                <path
                  d="M273.763265 313.469388m-49.632653 0a49.632653 49.632653 0 1 0 99.265306 0 49.632653 49.632653 0 1 0-99.265306 0Z"
                  fill="#E5404F"
                  p-id="12230"
                ></path>
                <path
                  d="M644.179592 768h-365.714286c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.897959h365.714286c11.493878 0 20.897959 9.404082 20.897959 20.897959s-9.404082 20.897959-20.897959 20.897959zM461.322449 670.82449h-182.857143c-11.493878 0-20.897959-9.404082-20.897959-20.897959s9.404082-20.897959 20.897959-20.89796h182.857143c11.493878 0 20.897959 9.404082 20.897959 20.89796s-9.404082 20.897959-20.897959 20.897959z"
                  fill="#0B9682"
                  p-id="12231"
                ></path>
              </svg>
              <p>请先在素材库中选择一张图片</p>
            </div>
          </div>
          <!-- 参数选择 -->
          <div class="bg-white rounded-lg border p-4">
            <div class="flex items-center gap-2">
              <h3 class="text-lg font-semibold mb-1">扩展参数</h3>
              <svg
                t="1753021580676"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="37693"
                width="30"
                height="30"
              >
                <path
                  d="M192 736c-54.4 0-96-41.6-96-96s41.6-96 96-96 96 41.6 96 96-41.6 96-96 96z m0-64c19.2 0 32-12.8 32-32s-12.8-32-32-32-32 12.8-32 32 12.8 32 32 32zM512 608c-54.4 0-96-41.6-96-96s41.6-96 96-96 96 41.6 96 96-41.6 96-96 96z m0-64c19.2 0 32-12.8 32-32s-12.8-32-32-32-32 12.8-32 32 12.8 32 32 32zM832 480c-54.4 0-96-41.6-96-96s41.6-96 96-96 96 41.6 96 96-41.6 96-96 96z m0-64c19.2 0 32-12.8 32-32s-12.8-32-32-32-32 12.8-32 32 12.8 32 32 32z"
                  fill="#50E3C2"
                  p-id="37694"
                ></path>
                <path
                  d="M192 96c19.2 0 32 12.8 32 32v320c0 19.2-12.8 32-32 32s-32-12.8-32-32V128c0-19.2 12.8-32 32-32zM832 544c19.2 0 32 12.8 32 32v320c0 19.2-12.8 32-32 32s-32-12.8-32-32V576c0-19.2 12.8-32 32-32zM512 96c19.2 0 32 12.8 32 32v192c0 19.2-12.8 32-32 32s-32-12.8-32-32V128c0-19.2 12.8-32 32-32zM512 672c19.2 0 32 12.8 32 32v192c0 19.2-12.8 32-32 32s-32-12.8-32-32v-192c0-19.2 12.8-32 32-32zM192 800c19.2 0 32 12.8 32 32v64c0 19.2-12.8 32-32 32s-32-12.8-32-32v-64c0-19.2 12.8-32 32-32zM832 96c19.2 0 32 12.8 32 32v64c0 19.2-12.8 32-32 32s-32-12.8-32-32V128c0-19.2 12.8-32 32-32z"
                  fill="#597EF7"
                  p-id="37695"
                ></path>
              </svg>
            </div>

            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium mb-2"
                  >扩展数量: {{ expandCount }}</label
                >
                <Slider
                  v-model="expandCountArray"
                  :min="1"
                  :max="12"
                  :step="1"
                  class="w-full"
                  @update:model-value="updateExpandCount"
                />
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                  <span>1张</span>
                  <span>12张</span>
                </div>
              </div>

              <div>
                <label class="block text-sm font-medium mb-2">生成风格</label>
                <Select v-model="expandStyle">
                  <SelectTrigger>
                    <SelectValue placeholder="选择生成风格" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="auto">自动风格</SelectItem>
                    <SelectItem value="realistic">写实风格</SelectItem>
                    <SelectItem value="artistic">艺术风格</SelectItem>
                    <SelectItem value="cartoon">卡通风格</SelectItem>
                    <SelectItem value="vintage">复古风格</SelectItem>
                    <SelectItem value="modern">现代风格</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label class="block text-sm font-medium mb-2"
                  >自定义提示词</label
                >
                <Textarea
                  v-model="customPrompt"
                  placeholder="例如：一个充满活力的城市夜景，或者保持原图风格但增加更多细节..."
                  class="min-h-[80px] resize-none"
                />
                <p class="text-xs text-gray-500 mt-1">
                  可选：添加特定要求或风格描述，让生成的图片更符合您的期望
                </p>
              </div>
            </div>

            <Button
              :disabled="!selectedImage || isExpanding"
              @click="expandImages"
              class="w-full flex items-center justify-center gap-2 mt-4"
              size="lg"
            >
              <svg
                v-if="isExpanding"
                class="w-4 h-4 animate-spin"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                />
              </svg>
              <svg
                v-else
                class="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M13 10V3L4 14h7v7l9-11h-7z"
                />
              </svg>
              {{ isExpanding ? "扩展中..." : "扩展生成" }}
            </Button>
          </div>
        </div>
      </ScrollArea>
      <!-- 右侧结果区域 -->
      <ScrollArea class="flex-1 rounded-md border p-4 h-[600px] bg-white">
        <div class="flex-shrink-0 mb-4">
          <h2 class="text-xl font-semibold">扩展结果</h2>
        </div>
        <div
          v-if="expandedImages.length === 0"
          class="flex flex-col items-center justify-center h-full text-gray-400 p-8"
        >
          <svg
            t="1753020583877"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="22959"
            width="150"
            height="150"
          >
            <path
              d="M945.23 671.992c0 27.614-22.385 50-50 50H228.769c-27.614 0-50-22.386-50-50V454.008c0-27.614 22.386-50 50-50H895.23c27.615 0 50 22.386 50 50v217.984z"
              fill="#33DEB4"
              opacity=".4"
              p-id="22960"
            ></path>
            <path
              d="M845.23 690.992H178.769c-38.598 0-70-31.402-70-70V403.008c0-38.598 31.402-70 70-70H845.23c38.598 0 70 31.402 70 70v217.984c0 38.598-31.402 70-70 70zM178.769 373.008c-16.542 0-30 13.458-30 30v217.984c0 16.542 13.458 30 30 30H845.23c16.542 0 30-13.458 30-30V403.008c0-16.542-13.458-30-30-30H178.769z"
              fill="#33DEB4"
              p-id="22961"
            ></path>
            <path
              d="M274.951 511m-60 0a60 60 0 1 0 120 0 60 60 0 1 0-120 0Z"
              fill="#33DEB4"
              p-id="22962"
            ></path>
            <path
              d="M622 239.695a19.943 19.943 0 0 1-14.143-5.858l-82.972-82.972c-3.441-3.442-8.018-5.337-12.886-5.337s-9.445 1.896-12.887 5.338l-82.971 82.971c-7.811 7.811-20.474 7.811-28.284 0s-7.811-20.474 0-28.284l82.971-82.972c10.998-10.997 25.619-17.053 41.171-17.053 15.553 0 30.174 6.056 41.171 17.053l82.972 82.972c7.81 7.811 7.81 20.474 0 28.284A19.934 19.934 0 0 1 622 239.695zM512 929.696c-15.552 0-30.174-6.057-41.171-17.054l-82.971-82.972c-7.811-7.811-7.811-20.475 0-28.285 7.812-7.809 20.475-7.809 28.284 0l82.971 82.972A18.107 18.107 0 0 0 512 889.696c4.868 0 9.444-1.896 12.886-5.338l82.972-82.973c7.811-7.811 20.475-7.811 28.285 0 7.81 7.811 7.81 20.475 0 28.285l-82.972 82.972c-10.997 10.998-25.618 17.054-41.171 17.054z"
              fill="#808080"
              p-id="22963"
            ></path>
          </svg>
          <p class="text-lg font-medium mb-2">暂无扩展结果</p>
          <p class="text-sm text-gray-500">选择图片并配置参数后点击扩展生成</p>
        </div>
        <div v-else class="space-y-4 p-4">
          <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-3 gap-3">
            <div
              v-for="(img, index) in expandedImages"
              :key="index"
              class="relative group"
            >
              <div
                class="rounded-lg overflow-hidden border border-gray-200 shadow-sm hover:shadow-md transition-shadow"
              >
                <img
                  :src="img.url"
                  :alt="img.name"
                  class="w-full h-32 object-cover"
                />
                <div class="p-2">
                  <div class="text-xs font-medium text-gray-800 mb-1 truncate">
                    {{ img.name }}
                  </div>
                  <div class="text-xs text-gray-500 line-clamp-2">
                    {{ img.description }}
                  </div>
                </div>
                <!-- 操作按钮 -->
                <div
                  class="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity"
                >
                  <div class="flex gap-1">
                    <Button
                      size="sm"
                      variant="secondary"
                      class="w-6 h-6 p-0"
                      @click="downloadImage(img)"
                    >
                      <svg
                        class="w-3 h-3"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                        />
                      </svg>
                    </Button>
                    <Button
                      size="sm"
                      variant="secondary"
                      class="w-6 h-6 p-0"
                      @click="addToMaterial(img)"
                    >
                      <svg
                        class="w-3 h-3"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                        />
                      </svg>
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 批量操作 -->
          <div class="mt-4 pt-3 border-t border-gray-200">
            <div class="flex justify-between items-center">
              <span class="text-sm text-gray-600"
                >共生成 {{ expandedImages.length }} 张扩展图片</span
              >
              <div class="flex gap-2">
                <Button size="sm" variant="outline" @click="downloadAllImages"
                  >批量下载</Button
                >
                <Button size="sm" variant="outline" @click="addAllToMaterial"
                  >全部添加到素材库</Button
                >
              </div>
            </div>
          </div>
        </div>
      </ScrollArea>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useMaterialStore } from "../stores/material";
import { Button } from "../components/ui/button";
import { ScrollArea } from "../components/ui/scroll-area";
import { Slider } from "../components/ui/slider";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../components/ui/select";
import { Textarea } from "../components/ui/textarea";
import { generateSimilarImage } from "../api/imageGenerate";
import UploadService from "../api/upload";
import { toast } from "vue-sonner";
import { Badge } from "../components/ui/badge";

const materialStore = useMaterialStore();

// 获取从素材库选择的基础图片（单选）
const selectedImage = computed(() => materialStore.getSelectedImageForAction());

// 扩展参数
const expandCount = ref(3);
const expandCountArray = ref([3]); // Slider 需要数组形式
const expandStyle = ref("auto");
const customPrompt = ref("");

// 更新扩展数量的函数
function updateExpandCount(value: number[] | undefined) {
  if (value && value.length > 0) {
    expandCount.value = value[0];
  }
}

// 扩展状态和结果
const isExpanding = ref(false);
const expandedImages = ref<
  Array<{
    id: string;
    url: string;
    name: string;
    description: string;
  }>
>([]);

// 扩展图片
async function expandImages() {
  if (!selectedImage.value) return;
  isExpanding.value = true;
  try {
    const res = await generateSimilarImage({
      originalImageId: Number(selectedImage.value.id),
      count: expandCount.value,
      style: expandStyle.value,
      customPrompt: customPrompt.value || undefined,
      userId: 1, // 这里可以根据实际登录用户获取
    });

    // 兼容接口返回格式
    if (res && res.data && Array.isArray(res.data)) {
      const baseImage = selectedImage.value;
      expandedImages.value = res.data.map((url: string, index: number) => ({
        id: `expanded_${Date.now()}_${index}`,
        url: url,
        name: `${baseImage?.name} 扩展版 ${index + 1}`,
        description: `风格：${expandStyle.value}，基于原图智能生成的相似风格图片`,
      }));

      toast.success(`成功生成 ${expandedImages.value.length} 张扩展图片`);
    } else {
      expandedImages.value = [];
      toast.error("生成扩展图片失败，请重试");
    }

    // 添加到历史记录
    materialStore.addHistory({
      id: Date.now().toString(),
      type: "expand",
      imageId: selectedImage.value?.id || "",
      content: `生成了 ${expandedImages.value.length} 张扩展图片`,
      time: Date.now(),
    });
  } catch (error) {
    console.error("图片扩展失败:", error);
    expandedImages.value = [];
    toast.error("图片扩展失败，请检查网络连接后重试");
  } finally {
    isExpanding.value = false;
  }
}

// 下载单张图片
function downloadImage(img: any) {
  const link = document.createElement("a");
  link.href = img.url;
  link.download = `${img.name}.jpg`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 添加到素材库
async function addToMaterial(img: any) {
  try {
    // 将图片 URL 转换为 File 对象
    const response = await fetch(img.url);
    const blob = await response.blob();
    const file = new File([blob], `${img.name}.jpg`, { type: "image/jpeg" });

    // 上传到后台
    const uploadResult = await UploadService.uploadSingle({
      file: file,
      userId: "1", // 这里可以根据实际登录用户获取
    });

    if (uploadResult.success && uploadResult.data) {
      // 上传成功后添加到前端 store
      const newImage = {
        id: uploadResult.data.id.toString(),
        url: uploadResult.data.url,
        name: img.name,
        originalName: img.originalName,
        tags: ["AI生成", "扩展图片"],
        uploadTime: Date.now(),
        usedCount: 0,
        isFavorite: false,
      };
      materialStore.addImages([newImage]);

      toast.success("图片已成功添加到素材库");
    } else {
      toast.error("添加到素材库失败，请重试");
    }
  } catch (error) {
    console.error("添加到素材库失败:", error);
    toast.error("添加到素材库失败，请检查网络连接后重试");
  }
}

// 批量下载
function downloadAllImages() {
  expandedImages.value.forEach(img => {
    setTimeout(() => downloadImage(img), 100);
  });
}

// 全部添加到素材库
async function addAllToMaterial() {
  try {
    const uploadPromises = expandedImages.value.map(async img => {
      // 将图片 URL 转换为 File 对象
      const response = await fetch(img.url);
      const blob = await response.blob();
      const file = new File([blob], `${img.name}.jpg`, { type: "image/jpeg" });

      // 上传到后台
      return UploadService.uploadSingle({
        file: file,
        userId: "1", // 这里可以根据实际登录用户获取
      });
    });

    const uploadResults = await Promise.all(uploadPromises);
    const successfulUploads = uploadResults.filter(result => result.success);

    if (successfulUploads.length > 0) {
      // 将成功上传的图片添加到前端 store
      const newImages = successfulUploads.map((result, index) => ({
        id: result.data.id.toString(),
        url: result.data.url,
        name: expandedImages.value[index].name,
        originalName: expandedImages.value[index].name,
        tags: ["AI生成", "扩展图片"],
        uploadTime: Date.now(),
        usedCount: 0,
        isFavorite: false,
      }));
      materialStore.addImages(newImages);

      toast.success(`成功添加 ${successfulUploads.length} 张图片到素材库`);
    } else {
      toast.error("批量添加到素材库失败，请重试");
    }
  } catch (error) {
    console.error("批量添加到素材库失败:", error);
    toast.error("批量添加到素材库失败，请检查网络连接后重试");
  }
}

function formatDate(timestamp: number) {
  const date = new Date(timestamp);
  return date.toLocaleDateString("zh-CN");
}
</script>
